<template>
  <div id="manageQuestionSubmitView">
    <a-form :model="searchParams" layout="inline" style="flex-wrap: nowrap">
      <a-form-item field="id" label="提交记录id" style="width: 180px">
        <a-input-number v-model="searchParams.id" placeholder="请输入id" />
      </a-form-item>
      <a-form-item field="questionTitle" label="题目名称" style="width: 200px">
        <a-input
          v-model="searchParams.questionTitle"
          placeholder="请输入题目名称"
        />
      </a-form-item>
      <a-form-item field="userId" label="用户id" style="width: 190px">
        <a-input-number v-model="searchParams.userId" placeholder="用户id" />
      </a-form-item>
      <a-form-item field="judgeResult" label="判题结果" style="width: 200px">
        <a-select
          v-model="searchParams.judgeResult"
          placeholder="判题结果"
          style="width: 200px"
          allow-clear
        >
          <a-option value="Accepted">Accepted</a-option>
          <a-option value="Wrong Answer">Wrong Answer</a-option>
          <a-option value="Memory Limit Exceeded"
            >Memory Limit Exceeded
          </a-option>
          <a-option value="Time Limit Exceeded">Time Limit Exceeded</a-option>
          <a-option value="Waiting">Waiting</a-option>
          <a-option value="Dangerous Code">Dangerous Code</a-option>
          <a-option value="Runtime Error">Runtime Error</a-option>
          <a-option value="System Error">System Error</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="status" label="运行结果" style="width: 215px">
        <a-select
          v-model="searchParams.status"
          placeholder="运行结果"
          style="width: 200px"
          allow-clear
        >
          <a-option value="1">判题中</a-option>
          <a-option value="2">代码执行成功</a-option>
          <a-option value="3">代码执行失败</a-option>
        </a-select>
      </a-form-item>
      <!-- 按钮组 -->
      <a-form-item style="flex-shrink: 0; margin-left: auto">
        <a-space :size="10" :wrap="false">
          <a-button type="primary" @click="doSubmit">查找</a-button>
          <!-- 新增清理按钮 -->
          <a-button
            type="primary"
            status="warning"
            @click="doCleanQuestionSubmit"
          >
            清理所有提交记录
          </a-button>
          <a-button
            type="primary"
            status="danger"
            :disabled="selectedIds.length === 0"
            @click="doBatchDelete"
          >
            批量删除（{{ selectedIds.length }}）
          </a-button>
          <a-checkbox v-model="allSelected" @change="handleSelectAll">
            全选
          </a-checkbox>
        </a-space>
      </a-form-item>
      <!-- 新增清理确认对话框 -->
      <a-modal
        v-model:visible="cleanModalVisible"
        title="确认清理"
        @ok="handleCleanConfirm"
        @cancel="cleanModalVisible = false"
      >
        <p>确定要清理所有提交记录吗？此操作不可恢复！</p>
        <template #footer>
          <a-button @click="cleanModalVisible = false">取消</a-button>
          <a-button type="primary" status="danger" @click="handleCleanConfirm">
            确定清理
          </a-button>
        </template>
      </a-modal>
    </a-form>
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="pagination"
      @sorter-change="handleSorterChange"
      @page-change="onPageChange"
    >
      <template #status="{ record }">
        {{ getStatusText(record.status) }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button status="danger" @click="doDelete(record)">删除</a-button>
        </a-space>
      </template>
      <!-- 新增勾选列 -->
      <template #selector="{ record }">
        <a-checkbox
          v-model="selectedIds"
          :value="record.id"
          @change="handleSelect()"
        />
      </template>
    </a-table>
    <a-modal
      v-model:visible="codeModalVisible"
      title="查看代码"
      :width="800"
      :body-style="{ padding: '12px 0' }"
      :mask-closable="false"
    >
      <div
        style="
          height: 500px; // 缩小总高度
          border: 1px solid var(--color-border);
          padding: 10px 15px; // 调整内边距
          box-sizing: border-box;
          position: relative; // 新增定位
        "
      >
        <CodeEditor
          v-if="codeModalVisible"
          style="height: calc(100% - 10px)"
          :code="currentCode"
          :readonly="true"
          :id="BigInt(0)"
          @handle-change="(v) => (currentCode = v)"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { h, onMounted, reactive, ref, watchEffect } from "vue";
import {
  QuestionSubmit,
  QuestionSubmitControllerService,
  QuestionSubmitQueryRequest,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { TableColumnData } from "@arco-design/web-vue";
import { IconCode } from "@arco-design/web-vue/es/icon";
import CodeEditor from "@/components/CodeEditor.vue";

const tableRef = ref();
const cleanModalVisible = ref(false);
const selectedIds = ref<number[]>([]);
const allSelected = ref(false);
const dataList = ref<Array<QuestionSubmit>>([]);
const total = ref<number>(0);
const searchParams = ref<QuestionSubmitQueryRequest>({
  id: undefined,
  questionTitle: undefined,
  judgeResult: undefined,
  userId: undefined,
  pageSize: 10,
  current: 1,
  sortField: undefined,
  sortOrder: undefined,
});
const pagination = reactive({
  ...searchParams.value,
  showTotal: true,
  total: total,
  showJumper: true,
});
const onPageChange = (current: number) => {
  selectedIds.value = [];
  allSelected.value = false;
  pagination.current = current;
  searchParams.value.current = current;
  loadData();
};
const loadData = async () => {
  const res = await QuestionSubmitControllerService.pageQueryQuestionSubmit(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data?.records ?? [];
    total.value = res.data?.total ?? 0;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const columns = ref<TableColumnData[]>([
  {
    title: "id",
    dataIndex: "id",
    width: 100,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "题目id",
    dataIndex: "questionId",
    width: 100,
  },
  {
    title: "题目标题",
    dataIndex: "questionTitle",
    ellipsis: true,
    tooltip: true,
    width: 200,
  },
  {
    title: "判题状态",
    dataIndex: "status",
    width: 150,
    slotName: "status",
  },
  {
    title: "学生代码",
    width: 120,
    render: ({ record }) =>
      h(
        "a-button",
        {
          type: "text",
          onClick: (e: MouseEvent) => {
            e.stopPropagation();
            currentCode.value = record.code;
            codeModalVisible.value = true;
          },
        },
        [
          h(IconCode, {
            style: { fontSize: "18px", color: "#1890ff" }, // Ant Design 蓝色
          }),
        ]
      ),
  },
  {
    title: "判题结果",
    dataIndex: "judgeResult",
    width: 200,
  },
  {
    title: "时间消耗",
    dataIndex: "timeUsed",
    // 关键修改点：自定义渲染时间消耗列
    render: ({ record }) => `${record.timeUsed ?? "--"} ms`,
    width: 100,
  },
  {
    title: "内存消耗",
    dataIndex: "memoryUsed",
    // 关键修改点：自定义渲染内存消耗列
    render: ({ record }) => `${record.memoryUsed ?? "--"} KB`,
    width: 100,
  },
  {
    title: "用户id",
    dataIndex: "userId",
    width: 100,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 170,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "修改时间",
    dataIndex: "updateTime",
    width: 170,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "操作",
    slotName: "optional",
    width: 100,
  },
  {
    title: "选择",
    slotName: "selector",
    width: 70,
  },
]);

const doDelete = async (questionSubmit: QuestionSubmit) => {
  message.loading("正在删除中~");
  const res = await QuestionSubmitControllerService.deleteQuestionSubmit({
    id: Number(questionSubmit.id),
  });
  if (res.code === 0) {
    message.success("删除成功");
    await loadData();
  } else {
    message.error(res.message ?? "删除失败");
  }
};
const codeModalVisible = ref(false);
const currentCode = ref("");

// 处理排序逻辑
const handleSorterChange = (
  dataIndex: string,
  direction: string // 明确声明字面量类型
) => {
  searchParams.value.sortField = dataIndex as
    | "id"
    | "createTime"
    | "updateTime";
  searchParams.value.sortOrder =
    direction === "ascend"
      ? "ascend"
      : direction === "descend"
      ? "descend"
      : undefined;

  loadData(); // 触发后端请求
};

// 状态映射表
const statusMap: Record<number, string> = {
  0: "待判题",
  1: "判题中",
  2: "成功",
  3: "失败",
};

// 获取状态文本
const getStatusText = (status: number) => {
  return statusMap[status] || "未知状态";
};

// 处理单个选择
const handleSelect = () => {
  allSelected.value = selectedIds.value.length === dataList.value.length;
};

const handleSelectAll = (value: boolean | (number | string | boolean)[]) => {
  // 类型断言确保是布尔值
  const checked = value as boolean;
  selectedIds.value = checked
    ? dataList.value.map((item) => item.id as number)
    : [];
};

// 新增批量删除方法
const doBatchDelete = async () => {
  if (selectedIds.value.length === 0) return;
  message.loading("正在删除中~");
  const res = await QuestionSubmitControllerService.batchDeleteQuestionSubmits({
    ids: selectedIds.value,
  });
  if (res.code === 0) {
    message.success(`成功删除 ${selectedIds.value.length} 条记录`);
    selectedIds.value = [];
    await loadData();
  } else {
    message.error(res.message ?? "批量删除失败");
  }
};

// 新增清理方法
const doCleanQuestionSubmit = async () => {
  cleanModalVisible.value = true;
};
const handleCleanConfirm = async () => {
  try {
    const res = await QuestionSubmitControllerService.cleanQuestionSubmit();
    if (res.code === 0) {
      message.success("清理成功");
      await loadData();
    } else {
      message.error(res.message ?? "清理失败");
    }
  } catch (error) {
    message.error("操作发生错误");
  } finally {
    cleanModalVisible.value = false;
  }
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  selectedIds.value = [];
  allSelected.value = false;
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>
<style></style>
